import { Button, DatePicker, Slider, message } from "antd";
import moment from "moment";
import React, { useCallback, useRef, useState } from "react";
import "../style/DateController.css";

const { RangePicker } = DatePicker;
const timeline = {
  display: "flex",
  position: "absolute",
  bottom: "20px",
  left: "50%",
  transform: "translateX(-50%)",
  width: "80%",
  background: "rgba(2, 16, 25, 0.7)",
  padding: "12px",
  borderRadius: "8px",
  zIndex: 100,
};

const TimelineController = ({ playHeatData, ChangeSource }) => {
  console.log(playHeatData, "playHeatData");
  const [currentTime, setCurrentTime] = useState(0);
  // 当 isPlaying 状态更新时，同步更新 useRef 的值
  const [isPlaying, setIsPlaying] = useState(false);
  const [dateArray, setDateArray] = useState([]);
  const [dateTip, setdateTip] = useState([]);
  // 使用 useRef 来存储 isPlaying 的值，确保在闭包中能获取到最新状态
  const isPlayingRef = useRef(isPlaying);
  // 使用 useRef 来存储定时器的 ID
  const intervalRef = useRef(null);
  const intervalheatRef = useRef(null);
  // 用于记录当前截取的起始索引
  const currentIndexRef = useRef(0);
  const disabledDate = (current) => {
    // 禁用当前日期之前的日期
    return current && current > moment().startOf("day");
  };
  React.useEffect(() => {
    isPlayingRef.current = isPlaying;

    if (isPlaying) {
      intervalheat();
      intervalRef.current = setInterval(() => {
        playAnimation();
      }, 500);
    } else {
      // 如果停止播放，清除定时器
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        clearInterval(intervalheatRef.current);
      }
    }

    // 组件卸载时清除定时器，避免内存泄漏
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [isPlaying]);

  // 示例数组，模拟 100 多条数据
  const dataArray = playHeatData;

  let currentIndex = 0;

  // 设置循环定时器
  const intervalheat = () => {
    intervalheatRef.current = setInterval(() => {
      // 计算本次要取出数据的结束索引
      const endIndex = Math.min(currentIndex + 10000, dataArray.length);
      // 取出当前的 10 条数据（或者最后不足 10 条的数据）
      const chunk = dataArray.slice(currentIndex, endIndex);
      ChangeSource(chunk);
      console.log(chunk, "====");

      // 更新索引
      currentIndex = endIndex;

      // 判断是否已经取完所有数据
      if (currentIndex >= dataArray.length) {
        // 取完数据，停止定时器
        clearInterval(intervalheatRef.current);
        console.log("数据已全部取出，定时器停止。");
      }
    }, 500);
  };

  const pushTip = () => {
    const arrayLength = dateArray.length;
    if (arrayLength === 0) return null;
    const newArray = dateArray.slice(
      currentIndexRef.current,
      currentIndexRef.current + 8
    );
    // 判断是否取到最后一个元素
    if (currentIndexRef.current + newArray.length >= dateArray.length) {
      setTimeout(() => {
        setIsPlaying(false);
      }, 500);
    }

    currentIndexRef.current += 8;
    if (currentIndexRef.current >= dateArray.length) {
      currentIndexRef.current = 0;
    }
    return newArray;
  };

  // 切换播放/暂停状态
  const togglePlay = () => {
    if (dateTip.length < 1) {
      message.warning("请选择日期");
      return;
    }
    setIsPlaying((prevIsPlaying) => {
      const newIsPlaying = !prevIsPlaying;

      return newIsPlaying;
    });
  };

  const playAnimation = () => {
    // 使用 useRef 存储的 isPlaying 值进行判断
    if (!isPlayingRef.current) return;
    setCurrentTime((prevTime) => {
      let newTime = prevTime + 1;
      if (newTime >= dateTip.length) {
        const Tip = pushTip();
        setdateTip(Tip);
        newTime = 0;
      }
      return newTime;
    });
  };

  // 处理日期范围改变事件
  const handleDateChange = (dates, dateStrings) => {
    const res = getDatesBetween(dateStrings[0], dateStrings[1]);
    const newres = getDatesBetween(dateStrings[0], dateStrings[1]);
    newres.splice(0, 8);
    setDateArray(newres);
    setdateTip(res.slice(0, 8));

    currentIndexRef.current = 0;
  };

  const getDatesBetween = useCallback((startDateStr, endDateStr) => {
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      return [];
    }
    const dates = [];
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, "0");
      const day = String(currentDate.getDate()).padStart(2, "0");
      dates.push(`${year}-${month}-${day}`);
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return dates;
  }, []);
  return (
    <div className="timeline-controller" style={timeline}>
      <div
        className="control-buttons"
        style={{ width: "30%", display: "flex" }}
      >
        <RangePicker
          disabledDate={disabledDate}
          allowClear={true}
          onChange={handleDateChange}
          format="YYYY-MM-DD"
        />
        <Button
          type="primary"
          onClick={togglePlay}
          style={{ marginLeft: "5px", marginRight: "5px" }}
        >
          {isPlaying ? "暂停" : "播放"}
        </Button>
      </div>
      <div style={{ width: "70%" }}>
        <div
          style={{
            position: "absolute",
            zIndex: 100,
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          {dateTip &&
            dateTip.map((item, index) => {
              return (
                <span key={index} style={{ color: "#fff", marginLeft: "20px" }}>
                  {item}
                </span>
              );
            })}
        </div>

        <Slider
          value={currentTime}
          onChange={(value) => setCurrentTime(value)}
          min={0}
          max={dateTip.length}
          step={1}
        />
      </div>
    </div>
  );
};

export default TimelineController;
